package controllers

import (
	"github.com/dchest/captcha"
	"mailsrv/utils"
	"strings"
	"mailsrv/models"
)

type PublicController struct {
	BaseController
}

func (this *PublicController) Prepare() {
	//先执行
	this.BaseController.Prepare()
}


func (this *PublicController) Login(){
	CaptchaId := captcha.NewLen(4)
	this.Data["CaptchaId"] = CaptchaId
	this.setTpl("login.html")
}
func (this *PublicController) LoginDo(){
	username := strings.TrimSpace(this.GetString("username"))
	password := strings.TrimSpace(this.GetString("password"))
	validcode := this.GetString("validcode")
	istruecode := this.checkCaptcha(validcode)
	if !istruecode {
		this.ajaxReturn("", "验证码填写错误", 403)
	}
	if len(username) == 0 || len(password) == 0 {
		this.ajaxReturn("", "用户名和密码不正确", 403)
	}
	password = utils.String2md5(password)

	user_info, err := models.GetOneAdminUser(username, password)
	if err != nil{
		this.ajaxReturn("","帐号或密码错误", 400)
	}
	this.SetUserLoginSess(user_info)
	welcome_url := this.URLFor("MainController.Welcome")
	this.ajaxReturn(map[string]string{"url":welcome_url},"登录成功", 200)
	this.Ctx.WriteString("##success login##")
}

//重新获取一个新的验证码地址
func (this *PublicController) GetCaptchaId(){
	id := captcha.NewLen(4)
	this.SetSession("captchaId", id)

	fresh_url := "/captcha/"+id+".png"
	this.ajaxReturn(fresh_url, "success", 200)
}

//检测验证码是否正确
func (this *PublicController) checkCaptcha(captchaValue string) bool{
	captchaIdInterface := this.GetSession("captchaId")

	var captchaId string
	switch v := captchaIdInterface.(type) {
	case string:
		captchaId = v
	}

	if !captcha.VerifyString(captchaId, captchaValue) {
		return false
	} else {
		return true
	}
	return true
}


func (this *PublicController) AbortPage(){
	sessionVal := this.GetSession("TOP_ABORT_MSG")
	message, _ := sessionVal.(string)

	this.Data["message"] = message
	this.setTpl("error.html")
}

func (this *PublicController) Logout(){
	this.ClearUserLoginSess()

	//登录页面地址
	urlstr := this.URLFor("PublicController.Login")
	this.Redirect(urlstr, 302)
	this.StopRun()
}



